package com.cmcc.driver.ui.profile.viewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cmcc.driver.data.DriverRequest
import com.cmcc.shared.model.MsgBean
import com.cmcc.driver.data.entity.response.CarInfo
import com.cmcc.shared.model.AppResponse
import com.cmcc.shared.model.DriverInfo
import com.cmcc.shared.utils.L
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Author: jiangxin
 * Date: 2019/11/15
 * Description:
 */
class ProfileViewModel : ViewModel() {

    val driverInfo = MutableLiveData<DriverInfo>()
    val carInfo = MutableLiveData<CarInfo>()

    val msgList = MutableLiveData<AppResponse<MsgBean>>()

    /**
     * 获取司机信息
     */
    fun getDriverInfo(){
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().getDriverInfo()
                if (response.isSuccessful) {
                    val data = response.body()
                    if (data?.code == 200) {
                        driverInfo.value = data.data
                    } else {
                        L.d("请求错误")
                    }
                } else {
                    L.d("服务器错误")
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    /**
     * 获取车辆信息及driverId
     */
    fun requestCarInfo() :MutableLiveData<CarInfo>{
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = DriverRequest.getInstance().getCarInfo()
                if (response.isSuccessful) {
                    val body = response.body()
                    if (body?.data?.isNotEmpty() == true){
                        carInfo.value = body.data[0]
                    }
                } else {
                    L.d("response failed")
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
        return carInfo
    }


    /**
     * 获取消息列表
     */
    fun list(pageNum: Int, pageSize: Int) :MutableLiveData<AppResponse<MsgBean>>{
        viewModelScope.launch(Dispatchers.Main) {
            val response = DriverRequest.getInstance().list(pageNum, pageSize)
            if (response.isSuccessful) {
                msgList.value = response.body()
            }

        }
        return msgList
    }

}